package com.nari.kmd_dataservice.init;

import com.nari.core.tool.utils.RedisUtil;
import com.nari.kmd_dataservice.constant.ConstantParameter;
import com.nari.kmd_dataservice.constant.GlobalVariable;
import com.nari.kmd_dataservice.mapper.ServerMapper;
import com.nari.kmd_dataservice.service.LoadPlatformService;
import com.nari.kmd_dataservice.util.NetworkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * @ClassName: KmdDataServiceInit
 * @Description: 初始化
 * @Author: zhangnaijiang
 * @Date: 2022/01/25 22:51
 * @Version 1.0.0
 */
@Component
@Order(2)
@Slf4j
public class KmdDataServiceInit implements CommandLineRunner {
    @Resource
    private ServerMapper serverMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private LoadPlatformService loadPlatformService;

    @Value("${kmd_dataservice.check.checkSM3}")
    private boolean checkSM3;
    @Value("${kmd_dataservice.check.checkSM4}")
    private boolean checkSM4;
    @Value("${kmd_dataservice.check.checkToken}")
    private boolean checkToken;

    @Override
    public void run(String... args) throws Exception {
        GlobalVariable.checkSM3 = checkSM3;
        GlobalVariable.checkSM4 = checkSM4;
        GlobalVariable.checkToken = checkToken;
        log.info("checkSM3={}, checkSM4={}, checkToken={}", checkSM3, checkSM4, checkToken);
        GlobalVariable.laUserList = serverMapper.selectLaUserList();
        log.info("负荷聚合平台账号{}", GlobalVariable.laUserList);
        if(CollectionUtils.isEmpty(GlobalVariable.laUserList)){
            throw new Exception("无负荷聚合平台账号，请检查数据库");
        }
        for(int i=0; i<GlobalVariable.laUserList.size(); i++){
            if(!NetworkUtil.checkUrl(GlobalVariable.laUserList.get(i).getUrl())){
                throw new Exception(GlobalVariable.laUserList.get(i)+"URL格式不正确");
            }
        }
        log.info("redis测试");
        Object redistest = redisUtil.get("redistest");
        log.info("redis测试结束{}",redistest);
        log.info("负荷聚合平台连接测试");
        for(int i=0; i<GlobalVariable.laUserList.size(); i++){
            try{
                loadPlatformService.targetVerify(GlobalVariable.laUserList.get(i));
            }catch (Exception e){
                log.error("负荷聚合平台连接异常",e);
            }
        }
        log.info("负荷聚合平台连接测试结束");
    }
}
